package com.fyzk.activity.fragment;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.fyzk.adapter.GameAllAdapter;
import com.fyzk.base.BaseFragment;
import com.fyzk.bean.GameInfoBean;
import com.fyzk.net.Commands;
import com.fyzk.utils.LogUtils;
import com.fyzk.view.DividerItemDecoration;
import com.tyjc.lottery.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import http.Common.CommandUtil;
import http.StringResultBean;

/**
 * <p>
 * @author Administrator
 * @mood
 * @description 比分-全部比赛
 * @date 2018/9/18 9:51
 * </p>
 */
public class GameAllFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // 全部  未开赛  进行中  已结束
    private String tabName;
    // 1 全部  2 未开赛  3 进行中  4 已结束
    private int tabType;

    private View mainView;

    private LinearLayoutManager mLayoutManager;
    private RecyclerView mRecyclerView;
    private SwipeRefreshLayout mRefreshLayout;
    private GameAllAdapter mAdapter;

    private boolean isRefresh = true;//是否刷新中
    private boolean isLoading;//是否加载中
    private int startIndex = 0;
    private int pageCount = 15;

    public static GameAllFragment newInstance(String tabName, int tabType) {
        GameAllFragment fragment = new GameAllFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, tabName);
        args.putInt(ARG_PARAM2, tabType);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            tabName = getArguments().getString(ARG_PARAM1);
            tabType = getArguments().getInt(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mainView = inflater.inflate(R.layout.fragment_score_child, null);
        initView();
        initData();
        initListener();
        return mainView;
    }

    private void initView() {
        mRecyclerView = mainView.findViewById(R.id.scoreChildFragUI_recyclerView);
        mRefreshLayout = mainView.findViewById(R.id.scoreChildFragUI_refreshLayout);
        mLayoutManager = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(2));
        mRefreshLayout.setColorSchemeResources(R.color.top_bg);
        mAdapter = new GameAllAdapter(getContext());
        mRecyclerView.setAdapter(mAdapter);
    }

    private void initData() {
        httpGameAll();
    }

    private void httpGameAll() {
        if(!isLoading) {
            isLoading = true;
            JSONObject request_json = new JSONObject();
            try {
                // 0:已结束 1:进行中 2:未开赛
                request_json.put("type", getGameType(tabType));
                request_json.put("startLine", startIndex);
                request_json.put("maxLine", pageCount);

                LogUtils.e("====request_json===="+request_json.toString());

                httpPostJson(CommandUtil.SCOREGEME, Commands.SCOREGAME, request_json, true);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);

        LogUtils.e("====onSuccess requestCode===="+requestCode);
        LogUtils.e("====onSuccess result===="+result);

        isLoading = false;
        isRefresh = false;
        mRefreshLayout.setRefreshing(false);
        List<GameInfoBean> gameInfoBeans = JSON.parseArray(resultBean.getData(), GameInfoBean.class);

        if (gameInfoBeans == null || gameInfoBeans.size() == 0) {
            if (startIndex == 0) {
                mAdapter.setHeadData(true);
                mAdapter.getData().clear();
                mAdapter.notifyDataSetChanged();
            } else {
                //设置回到上拉加载更多
                mAdapter.changeMoreStatus(mAdapter.NO_LOAD_MORE);
                showToast("没有更多数据了");
            }
        } else {
            mAdapter.setHeadData(false);
            //设置回到上拉加载更多
            mAdapter.changeMoreStatus(mAdapter.NO_LOAD_MORE);
            if (startIndex == 0) {
                mAdapter.setData(gameInfoBeans);
            } else {
                mAdapter.getData().addAll(gameInfoBeans);
                mAdapter.notifyDataSetChanged();
            }
            startIndex += gameInfoBeans.size();
        }
    }

    @Override
    public void onFailure(int requestCode, String errorCode, String message) {
        LogUtils.e("====onFailure errorCode===="+errorCode);
        LogUtils.e("====onFailure message===="+message);
        isLoading = false;
        isRefresh = false;
        mRefreshLayout.setRefreshing(false);
        showToast(message);
    }

    private void initListener() {
        mRefreshLayout.setOnRefreshListener(this);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            boolean isSlidingToLast = false;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    int lastVisibleItem = mLayoutManager.findLastCompletelyVisibleItemPosition();
                    int totalItemCount = mLayoutManager.getItemCount();

                    // isSlidingToLast 第一页显示的Item条数高度需要大于屏幕
                    if (lastVisibleItem == (totalItemCount - 1) && isSlidingToLast) {
                        //设置正在加载更多
                        mAdapter.changeMoreStatus(mAdapter.LOADING_MORE);
                        httpGameAll();
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (dy > 0)
                    isSlidingToLast = true;
                else
                    isSlidingToLast = false;
            }
        });
    }

    @Override
    public void onRefresh() {
        if(!isRefresh) {
            isRefresh = true;
            startIndex = 0;
            httpGameAll();
        }
    }

    /**
     * @param tabType
     * @return
     */
    private String getGameType(int tabType){
        String gameType = "";
        switch (tabType){
            case 1:
                // 全部
                gameType = "";
                break;
            case 2:
                // 未开赛
                gameType = "2";
                break;
            case 3:
                // 进行中
                gameType = "1";
                break;
            case 4:
                // 已结束
                gameType = "0";
                break;
        }
        return gameType;
    }

}
